<script setup lang="ts">
import { propTypes } from '@/utils/propTypes'
import { ref, unref, watch } from 'vue'
import { unitDeptTree } from '@/components/unit'
import { useUserStoreWithOut } from '@/store/modules/user'
import { getBasics, query } from '@/api/emp/emp'
import { Table, TableColumn } from '@/components/Table'
import { HrUserType, HrItemDic } from '@/config/publicDic'
import { FormSchema } from '@/components/Form'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
const emit = defineEmits(['update:visible', 'close', 'save'])
import { ElMessage } from 'element-plus'
const minHeight = ref('500px')
const subTitle = ref('用户列表')
const userStore = useUserStoreWithOut()
let empCache = {}
const curKey = ref<string[]>([])
const curEmp = ref<any[]>([])
const loading = ref<boolean>(false)
const emps = ref([])
const empVisible = ref<boolean>(false)
let comId = null
const props = defineProps({
  title: propTypes.string,
  visible: propTypes.bool.def(false),
  empId: propTypes.arrayOf(propTypes.string),
  companyId: propTypes.string,
  value: propTypes.any,
  status: propTypes.array.def([1]),
  isMultiple: propTypes.bool.def(false),
  isAllowNull: propTypes.bool.def(true),
  isSubCompany: propTypes.bool.def(false),
  unitId: propTypes.array,
  deptId: propTypes.array,
  titleCode: propTypes.arrayOf(propTypes.string).def([]),
  postCode: propTypes.arrayOf(propTypes.string).def([]),
  isEntry: propTypes.bool,
  isLeader: propTypes.bool
})
const queryParam = ref({
  QueryKey: null,
  UnitId: props.unitId,
  DeptId: props.deptId,
  CompanyId: comId,
  Status: props.status,
  IsEntry: props.isEntry,
  Post: props.postCode,
  Title: props.titleCode,
  IsLeader: props.isLeader
})
const paging = ref({
  defaultPageSize: 10,
  pageSize: 10,
  total: 0,
  hideOnSinglePage: false
})
const schema: FormSchema[] = [
  {
    field: 'QueryKey',
    label: '关键字',
    component: 'Input',
    componentProps: {
      placeholder: '人员名\编号\手机号'
    }
  },
  {
    field: 'Post',
    label: '岗位',
    component: 'TreeDicItem',
    componentProps: {
      placeholder: '人员岗位',
      dicId: HrItemDic.post,
      isMultiple: true
    }
  },
  {
    field: 'Title',
    label: '职务',
    component: 'DicItem',
    componentProps: {
      placeholder: '人员职务',
      dicId: HrItemDic.title,
      multiple: true
    }
  }
]
const columns: TableColumn[] = [
  {
    field: 'EmpNo',
    label: '人员编号',
    align: 'center',
    width: '110px',
    sortable: 'custom'
  },
  {
    field: 'EmpName',
    label: '员工名',
    align: 'left',
    sortable: true
  },
  {
    field: 'Dept',
    label: '部门',
    align: 'left',
    sortable: 'custom',
    sortBy: 'DeptId'
  },
  {
    field: 'Phone',
    label: '手机号',
    align: 'center',
    sortable: true
  },
  {
    field: 'Post',
    label: '岗位',
    align: 'left',
    slotName: 'empPost'
  },
  {
    field: 'DeptTitle',
    label: '职务',
    align: 'left',
    slotName: 'empTitle'
  },
  {
    field: 'UserType',
    label: '人员类型',
    align: 'center',
    ortable: true,
    slotName: 'userType'
  }
]

const closeForm = function () {
  emit('update:visible', false)
  emit('close')
}
const reset = function () {
  subTitle.value = '用户列表'
  empCache = {}
  minHeight.value = window.innerHeight * 0.6 + 'px'
  comId = props.companyId == null || props.companyId == '' ? userStore.comId : props.companyId
  queryParam.value.CompanyId = comId
  if (props.empId != null && props.empId.length !== 0) {
    curKey.value = props.empId as string[]
    loadEmp()
  } else {
    curEmp.value = []
    curKey.value = []
  }
  loadGrid(null)
}
const loadEmp = async function () {
  const emps = await getBasics(comId, props.empId)
  emps.forEach((c) => {
    empCache[c.EmpId] = c
  })
  curEmp.value = emps
}
const selected = () => {
  loading.value = true
  if (curKey.value.length === 0) {
    curEmp.value = []
  } else {
    curEmp.value = curKey.value.map((c) => empCache[c])
  }
  loading.value = false
}
const loadGrid = async function (curPaging) {
  if (curPaging == null) {
    const cur = paging.value
    curPaging = {
      Size: cur.pageSize,
      Index: 1,
      SortName: 'EmpId',
      IsDesc: true
    }
  }
  loading.value = true
  const res = await query(queryParam.value, curPaging)
  paging.value.total = res.Count
  emps.value = res.List
  if (res.List != null) {
    res.List.forEach((c) => {
      empCache[c.EmpId] = c
    })
  }
  loading.value = false
}
const chioceDept = function (deptId, e) {
  const query = queryParam.value
  if (deptId.length === 0) {
    subTitle.value = e.comName[comId] + '公司-用户列表'
    query.UnitId = props.unitId
    query.DeptId = []
  } else {
    const dept = e.value[0]
    if (dept.type === 'unit') {
      subTitle.value = dept.Name + '单位-用户列表'
      query.UnitId = [dept.Id]
      query.DeptId = []
    } else {
      subTitle.value = dept.Name + '部门-用户列表'
      query.UnitId = [dept.UnitId]
      query.DeptId = [dept.Id]
    }
  }
  loadGrid(null)
}
const handleSearch = function (data) {
  const query = queryParam.value
  query.Title = data.Title
  query.Post = data.Post
  query.QueryKey = data.QueryKey
  loadGrid(null)
}
const save = () => {
  if (props.isAllowNull === false && (curKey.value == null || curKey.value.length === 0)) {
    ElMessage.warning('请选择人员!')
    return
  }
  const keys = unref(curKey)
  emit('update:visible', false)
  emit('save', {
    isMultiple: props.isMultiple,
    comId: comId,
    user: keys.map((c) => empCache[c]),
    keys: keys
  })
}
const drop = (item) => {
  let index = curEmp.value.findIndex((c) => c.EmpId == item.EmpId)
  if (index != -1) {
    curEmp.value.splice(index, 1)
    index = curKey.value.findIndex((c) => c == item.EmpId)
    curKey.value.splice(index, 1)
  }
}
watch(
  () => props.visible,
  (val: boolean) => {
    empVisible.value = val
    if (val) {
      reset()
    }
  },
  {
    immediate: true
  }
)
</script>
<template>
  <Dialog
    :title="title"
    :fullscreen="true"
    v-model="empVisible"
    width="80%"
    maxHeight="780px"
    :before-close="closeForm"
  >
    <div class="choiceEmp">
      <el-row :gutter="24">
        <el-col :span="6">
          <ContentWrap title="单位部门">
            <unitDeptTree
              ref="deptTree"
              :unit-id="unitId"
              :dept-id="deptId"
              :is-sub-company="isSubCompany"
              :company-id="comId"
              @change="chioceDept"
            />
          </ContentWrap>
        </el-col>
        <el-col :span="18">
          <ContentWrap :title="subTitle">
            <div class="app-container">
              <Search
                ref="search"
                :schema="schema"
                :model="queryParam"
                :is-col="false"
                layout="inline"
                :showSearch="true"
                button-position="left"
                :search-loading="loading"
                :reset-loading="loading"
                @search="handleSearch"
                @reset="handleSearch"
              />
            </div>
            <div>
              <span>已选：</span>
              <el-space>
                <el-tag v-for="i in curEmp" :key="i.EmpId" @close="drop(i)" closable>{{
                  i.EmpName
                }}</el-tag>
              </el-space>
            </div>
            <Table
              :columns="columns"
              :data="emps"
              :loading="loading"
              :pagination="paging"
              :isSelect="true"
              row-key="EmpId"
              v-model:selectKey="curKey"
              :is-multiple="isMultiple"
              :defaultSort="{ prop: 'EmpId', isDesc: true }"
              @selected="selected"
              @change="loadGrid"
            >
              <template #userType="e">
                {{ HrUserType[e.row.UserType].text }}
              </template>
              <template #empTitle="e">
                <template v-if="e.row.EntryTitle">
                  <p>{{ e.row.EntryTitle.Name }}</p>
                  <el-tooltip
                    v-if="e.row.Title && e.row.Title.length > 0"
                    effect="dark"
                    placement="bottom"
                  >
                    <template #content>
                      <div>
                        <p v-for="(t, index) in e.row.Title" :key="index">
                          {{ t.Show }}
                        </p>
                      </div>
                    </template>
                    <Icon icon="ep:more" />
                  </el-tooltip>
                </template>
                <template v-else-if="e.row.Title && e.row.Title.length > 0">
                  <p>{{ e.row.Title[0].Show }}</p>
                  <el-tooltip v-if="e.row.Title.length > 1" effect="dark" placement="bottom">
                    <template #content>
                      <div>
                        <p v-for="(t, index) in e.row.Title" :key="index">
                          {{ t.Show }}
                        </p>
                      </div>
                    </template>
                    <Icon icon="ep:more" />
                  </el-tooltip>
                </template>
              </template>
              <template #empPost="e">
                <template v-if="e.row.EntryPost">
                  <p> {{ e.row.EntryPost.Name }}</p>
                  <el-tooltip
                    v-if="e.row.Post && e.row.Post.length > 0"
                    effect="dark"
                    placement="bottom"
                  >
                    <template #content>
                      <div>
                        <p v-for="(t, index) in e.row.Post" :key="index">
                          {{ t.Show }}
                        </p>
                      </div>
                    </template>
                    <Icon icon="ep:more" />
                  </el-tooltip>
                </template>
                <template v-else-if="e.row.Post && e.row.Post.length > 0">
                  <p> {{ e.row.Post[0].Show }}</p>
                  <el-tooltip v-if="e.row.Post.length > 1" effect="dark" placement="bottom">
                    <template #content>
                      <div>
                        <p v-for="(t, index) in e.row.Post" :key="index">
                          {{ t.Show }}
                        </p>
                      </div>
                    </template>
                    <Icon icon="ep:more" />
                  </el-tooltip>
                </template>
              </template>
            </Table>
          </ContentWrap>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <el-space style="text-align: center; margin-top: 20px">
        <el-button @click="reset">重 置</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </el-space>
    </template>
  </Dialog>
</template>

<style type="less" scoped>
.choiceEmp {
  width: 98%;
}
.choiceEmp p {
  margin: 0;
  padding: 0;
}
.el-dialog footer {
  text-align: center !important;
}
</style>
